<template>
  <div class="environment-info container-bottom-20">
    <CardBox 
      title="物种统计" 
      :showTimeRange="true"
      :timeRange="timeRange"
      @date-change="handleDateChange">
    </CardBox>
    <div class="content-container">
      <div class="species-statistics-layout">
        <div class="statistics-chart" ref="speciesChart"></div>
      </div>
    </div>
  </div>
</template>

<script>
import CardBox from '@/components/Global/CardBox.vue'
import * as echarts from 'echarts'
import {EventBus} from "../../utils/event-bus";
import 'echarts-wordcloud'
export default {
  name: 'SpeciesStatistics',
  components: {
    CardBox
  },
  created() {
    EventBus.$on('set-device-type', (message) => {
      this.type=message;
      this.getData();
    });
    EventBus.$on('sent-device-id-to-right', (message) => {
      this.deviceId = message.id;
      this.getData();
    });
  },
  data() {
    return {
      deviceId:'',
      type:'hongwai',
      selectDate:null,
      timeRange:this.getDateRange(),
      chartData: [
        {
          name: '珠颈斑鸠',
          value: 300,
          itemStyle: { color: '#25CDE9' }
        },
        {
          name: '白胸鸭',
          value: 200,
          itemStyle: { color: '#3DD78C' }
        },
        {
          name: '灰喜鹊',
          value: 180,
          itemStyle: { color: '#3DD78C' }
        },
        {
          name: '乌鸦',
          value: 100,
          itemStyle: { color: '#3B7EFF' }
        },
        {
          name: '寒鸦',
          value: 80,
          itemStyle: { color: '#8E65FF' }
        }
      ]
    }
  },
  watch: {
    '$route.query': {
      handler(newQuery, oldQuery) {
        // 当路由的query参数发生变化时，执行这里的代码
        this.type=newQuery.deviceType;
        this.getData();
      },
      deep: true, // 设置为true以深度观察对象内部的变化
      immediate: true // 组件创建时立即执行一次
    }
  },
  mounted() {
    this.type=this.$route.query.deviceType;
    this.$nextTick(() => {
      this.getData();
    })
  },
  methods: {
    getDateRange(){
      let endDate=new Date();
      let startDate=new Date();
      startDate.setDate(endDate.getDate()-365);
      return [this.getDate(startDate),this.getDate(endDate)];
    },
    getDate(date){
      // const currentDate = new Date();
      const year = date.getFullYear();
      const month = date.getMonth() + 1; // 月份从0开始，需要加1
      const day = date.getDate();
      const today=`${year}-${month}-${day}`+' 00:00:00';
      // const lastYear=`${year}-${month}-${day-10}`+' 00:00:00';
      return today;
    },
    getData(){
      if(!this.selectDate){
        const currentDate = new Date();
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth() + 1; // 月份从0开始，需要加1
        const day = currentDate.getDate();
        const today=`${year}-${month}-${day}`;
        const lastYear=`${year-1}-${month}-${day}`;
        EventBus.$emit('set-date', [lastYear,today]);
        this.selectDate=[lastYear,today];
      }
      if(this.selectDate){
        this.$api.species.getStaticBydate(this.type,this.selectDate[0],this.selectDate[1],this.deviceId).then(res => {
          this.chartData = res;
          if(res&&res.length){
            this.initChart()
          }
        });
      }
    },
    handleDateChange(dateRange) {
      console.log('选择的日期范围:', dateRange)
      this.selectDate=dateRange;
      this.getData();
      // 这里可以根据选择的日期范围更新图表数据
      // 例如调用API获取新的数据
      // this.fetchDataByDateRange(dateRange)
    },
    initChart() {
      const chartDom = this.$refs.speciesChart
      if (!chartDom) return

      const chart = echarts.init(chartDom)

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: function (params) {
            // 自定义显示内容
            return `${params.name}: ${params.value}`;
          }
        },
        series: [{
          type: 'treemap',
          data: this.chartData,
          nodeClick: false,
          width: '100%',
          height: '100%',
          label: {
            show: true,
            formatter: '{b}',
            fontSize: 14,
            color: '#fff',
            position: 'inside'
          },
          itemStyle: {
            borderColor: 'rgba(0, 24, 106, 0.8)',
            borderWidth: 1,
            gapWidth: 2
          },
          breadcrumb: {
            show: false
          }
        }]
      }

      chart.setOption(option);
      chart.on('click', function (params) {
        if (params.componentType === 'series' && params.seriesType === 'treemap') {
          // 在这里添加你的点击处理逻辑，例如显示弹窗或更改数据等。
          console.log('点击了节点:', params.name);
          EventBus.$emit('select-species-name', params.name);
        }
      });
    }
  }
}
</script>

<style scoped lang="scss">
.species-statistics-layout {
  height: 242px;
  padding: 10px;
}

.statistics-chart {
  width: 100%;
  height: 100%;
  margin: 0 auto;
}

.date-picker {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  color: #fff;
  font-size: 14px;
  cursor: pointer;
  
  &:hover {
    color: #07FFE5;
  }
}
</style>
